//
//  VideoViewController.m
//  MeiShiDa
//
//  Created by zby on 15/6/30.
//  Copyright (c) 2015年 zby. All rights reserved.
//

#import "VideoViewController.h"
#import "VideoDetailViewController.h"
#import "VideoTableViewCell.h"
#import "TFHpple.h"
#import <MJRefresh.h>
#import <SVProgressHUD.h>

#import <AFNetworking.h>
@interface VideoViewController ()<UITableViewDataSource,UITableViewDelegate,VideoTableViewCellDelegate>


@property(nonatomic,strong)NSMutableArray *dataSourceArr;

@property(nonatomic,strong)UITableView *mainTableView;
@property(nonatomic,assign)NSInteger start;



@end

@implementation VideoViewController


//懒加载

- (UITableView *)mainTableView{
    if (!_mainTableView) {
        self.mainTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    }
    return _mainTableView;
}
- (NSMutableArray *)dataSourceArr{
    if (!_dataSourceArr) {
        self.dataSourceArr = [[NSMutableArray alloc]init];
    }
    return _dataSourceArr;
}




//请求完毕后让代理对象执行该方法，把请求完整的data传给代理对象
//- (void)requestDidFinshWithData:(NSData *)data{
//    TFHpple *xpathParser = [TFHpple hppleWithData:data isXML:YES];
//
//        NSArray *elements  = [xpathParser searchWithXPathQuery:@"//item"];
//        NSArray *elementsTitle  = [xpathParser searchWithXPathQuery:@"//item/title"];
//        NSArray *elementsImage  = [xpathParser searchWithXPathQuery:@"//item/listpicurl"];
//        NSArray *elementsVideo  = [xpathParser searchWithXPathQuery:@"//item/medialink"];
//        NSArray *elementsDate  = [xpathParser searchWithXPathQuery:@"//item/pubdate"];
//
//
//
//        for (int i=0; i<[elementsImage count];i++ ) {
//            VideoModel *model=[[VideoModel alloc]init];
//            model.title=[[ [elementsTitle objectAtIndex:i]firstChild] content];;
//            model.image=[[elementsImage objectAtIndex:i]content];
//            model.url=[[[elementsVideo objectAtIndex:i] firstChild]content];
//            model.date=[[elementsDate objectAtIndex:i]content];
//            [self.dataSourceArr addObject:model];
//        }
//    [_mainTableView reloadData];
//
//
//}
////请求失败后把错误原因传给代理对象
//- (void)requestError:(NSError *)error{
//    NSLog(@"%@",error);
//}







//请求数据  生成数据源   请求数据 以后写在model里
-(void)createData{
    NSString *urlStr = [NSString stringWithFormat:@"http://www.app360.cn/mobile/supportpages.jspx?id=Zchannel$06bea319-5900&s=10&t=1&curpage=%ld",(long)_start];


    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: urlStr]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        [SVProgressHUD popActivity];
        
        TFHpple *xpathParser = [TFHpple hppleWithData:responseObject isXML:YES];
    
        NSArray *elementsTitle  = [xpathParser searchWithXPathQuery:@"//item/title"];
        NSArray *elementsImage  = [xpathParser searchWithXPathQuery:@"//item/listpicurl"];
        NSArray *elementsVideo  = [xpathParser searchWithXPathQuery:@"//item/medialink"];
        NSArray *elementsDate  = [xpathParser searchWithXPathQuery:@"//item/pubdate"];
 
        if ([elementsTitle count]==0) {
            //没有更多数据
            [_mainTableView.footer noticeNoMoreData];
            return;
        }else{
            [_mainTableView.footer resetNoMoreData];
        }
        
        
        for (int i=0; i<[elementsImage count];i++ ) {
            VideoModel *model=[[VideoModel alloc]init];
            model.title=[[[elementsTitle objectAtIndex:i] firstChild]content];
            model.image=[[elementsImage objectAtIndex:i] content];
            model.url=[[[elementsVideo objectAtIndex:i] firstChild]content];
            model.date=[[elementsDate objectAtIndex:i]content];
            [self.dataSourceArr addObject:model];
        }
        [_mainTableView.header endRefreshing];
        [_mainTableView.footer endRefreshing];
        [_mainTableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@", error);
        [SVProgressHUD dismiss];
        [_mainTableView.header endRefreshing];
        [_mainTableView.footer endRefreshing];
    }];
    [operation start];  
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=NO;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.724 green:0.389 blue:1.000 alpha:1.000];
    _start=1;
    self.navigationItem.title=@"食频";
    [SVProgressHUD show];
    [self createData];
    [self creatMainTableView];
    
    [self.mainTableView reloadData];
    
}



// 添加传统的下拉刷新
-(void)addFresh{
    
    //添加头尾控件
    _mainTableView.header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downFresh:)];
    _mainTableView.footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upFresh)];
}

-(void)downFresh:(MJRefreshHeader *)header{
    
    self.start=1;
    [self.dataSourceArr removeAllObjects];
    [self createData];
}

-(void)upFresh{
    _start+=1;
    [self createData];
}







//创建mainTableView
-(void)creatMainTableView{
    self.mainTableView.frame=[UIScreen mainScreen].bounds;
    NSLog(@"___________%@", NSStringFromCGRect(self.mainTableView.frame));
    self.mainTableView.dataSource=self;
    self.mainTableView.delegate=self;
    [_mainTableView registerClass:[VideoTableViewCell class] forCellReuseIdentifier:@"cell1"];
    [self.view addSubview:self.mainTableView];
    [self addFresh];
//    self.navigationController.navigationBar.translucent = NO;
//    self.automaticallyAdjustsScrollViewInsets = NO;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  100;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [_dataSourceArr count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
//    cell.frame = CGRectMake(-SCREEN_WIDTH, 0, cell.frame.size.width, cell.frame.size.height);
    cell.delegate=self;
//    [UIView animateWithDuration:1 animations:^{
//        cell.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
//    }];
    if ([_dataSourceArr count]>1) {
        VideoModel *model=_dataSourceArr[indexPath.row];
    
        cell.video=model;
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    VideoDetailViewController *detailVC = [[VideoDetailViewController alloc]init];
    VideoModel *model=_dataSourceArr[indexPath.row];
    detailVC.passURLStr=model.url;
    detailVC.titleStr=model.title;
    [self.navigationController pushViewController:detailVC animated:YES];
    
}




//cell代理  传递button时间
-(void)videoCell:(VideoTableViewCell *)cell{
    VideoDetailViewController *detailVC = [[VideoDetailViewController alloc]init];
    VideoModel *model=cell.video;
    detailVC.passURLStr=model.url;
    detailVC.titleStr=model.title;
    [self.navigationController pushViewController:detailVC animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
